package com.yicong.ants.ui.hotel;

import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.cchao.simplelib.Const;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.ImageLoader;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseStatefulActivity;
import com.cchao.simplelib.util.StringHelper;
import com.cchao.simplelib.util.UrlUtil;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.databinding.HotelActivityBinding;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.ui.find.YcWebViewActivity;
import com.yicong.ants.utils.AmapHelper;
import com.yicong.ants.utils.L;
import com.yicong.ants.utils.StatusBarUtil;
import com.yicong.ants.utils.TimeHelper;
import com.yicong.ants.view.dialog.GpsDialog;
import com.yicong.ants.view.dialog.InDateDialog;
import com.yicong.ants.view.dialog.ProvinceDialog;

import java.util.HashMap;
import java.util.Map;


/**
 * 酒店首页
 */
public class HotelActivity extends BaseStatefulActivity<HotelActivityBinding> implements View.OnClickListener {

    private final String TAG = "HotelActivity";
    private String province;
    private String startDate;
    private String endDate;
    Map<String, String> mProvinceMap = new HashMap<>();

    @Override
    protected int getLayout() {
        return R.layout.hotel_activity;
    }

    @Override
    protected void initEventAndData() {
        mDataBind.setClick(this);
        StatusBarUtil.setStatusBarTransparent(this);
        showRule();
        checkGps();
        AmapHelper.startLocation(mContext, this::locationCallBack);
        initDate(TimeHelper.formatCurTime("yyyy-MM-dd"), TimeHelper.formatNextTime("yyyy-MM-dd"));
    }

    private void initDate(String startDate, String endDate) {
        L.i("startDate:" + startDate + ",endDate:" + endDate);
        this.startDate = startDate;
        this.endDate = endDate;
        mDataBind.tvStartDate.setText(TimeHelper.getFormattedTime(startDate, "yyyy-MM-dd", "MM月dd日"));
        mDataBind.tvEndDate.setText(TimeHelper.getFormattedTime(endDate, "yyyy-MM-dd", "MM月dd日"));
        mDataBind.tvTotalDate.setText(String.format("共%s晚", TimeHelper.differentDays(startDate, endDate)));
    }

    @Override
    protected void onLoadData() {

    }

    private void showRule() {
        ImageView imageView = mDataBind.ivHotelRule;
        ViewGroup.LayoutParams lp = imageView.getLayoutParams();
        lp.width = UiHelper.getScreenWidth();
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        imageView.setLayoutParams(lp);
        imageView.setMaxWidth(UiHelper.getScreenWidth());
        imageView.setMaxHeight(UiHelper.getScreenWidth() * 3);
        ImageLoader.loadImage(imageView, ZzConfigs.getClientConf().getHotel_rule_image());
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (R.id.tv_back == viewId) {
            finish();
        } else if (R.id.tv_order == viewId) {
            Router.turnTo(this, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, Constants.getWebUrl("hotel") + "myorder.html")
                .putExtra(Const.Extra.Web_View_Title_Visible, false)
                .checkLogin(true)
                .start();

        } else if (R.id.ll_choose_address == viewId) {
            chooseAddress();
        } else if (R.id.ll_load_location_info == viewId) {
            AmapHelper.startLocation(mContext, this::locationCallBack);
        } else if (R.id.ll_date == viewId) {
            showInDateDialog();
        } else if (R.id.btn_search == viewId) {
            if (!checkInput()) {
                return;
            }

            trimProvince();

            Map<String, String> map = new HashMap<>();
            map.put("token", UserManager.getUserBean().getJwt_token());
            map.put("start_date", startDate);
            map.put("end_date", endDate);
            map.put("keywords", StringHelper.null2Space(mDataBind.etKeyword.getText().toString()));
            map.put("lng", String.valueOf(AmapHelper.mAMapLocation.getLongitude()));
            map.put("lat", String.valueOf(AmapHelper.mAMapLocation.getLatitude()));
            map.put("position", province);
            map.put("province", province);
            map.put("curCity", province);
            map.put("curposition", province);

            Router.turnTo(mContext, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, UrlUtil.buildUrl(Constants.getWebUrl("hotel") + "hotel_list.html", map))
                .putExtra(Const.Extra.Web_View_Title_Visible, false)
                .start();
        }
    }

    private void trimProvince() {
        province = province.replaceAll("市", "");
        province = province.replaceAll("省", "");

        if (CollectionHelper.isEmpty(mProvinceMap)) {
            mProvinceMap.put("内蒙古自治区", "内蒙古");
            mProvinceMap.put("广西壮族自治区", "广西");
            mProvinceMap.put("西藏自治区", "西藏");
            mProvinceMap.put("宁夏回族自治区", "宁夏");
            mProvinceMap.put("新疆维吾尔自治区", "新疆");
            mProvinceMap.put("澳门特别行政区", "澳门");
            mProvinceMap.put("香港特别行政区", "香港");
        }

        if (mProvinceMap.containsKey(province)) {
            province = mProvinceMap.get(province);
        }
    }

    private boolean checkInput() {
        if (StringHelper.isEmpty(mDataBind.tvShowAddress.getText().toString())) {
            UiHelper.showToast("请选择地址");
            return false;
        }

        return true;
    }

    private void showInDateDialog() {
        InDateDialog.newInstance(this)
            .setConvertListener(this::initDate)
            .show(getSupportFragmentManager());
    }

    private void chooseAddress() {
        ProvinceDialog.newInstance(this)
            .setConvertListener(itemBean -> {
                province = itemBean.getName();
                mDataBind.tvShowAddress.setText(itemBean.getName());
            })
            .show(getSupportFragmentManager());
    }

    //获取定位信息;如果没有定位信息，可能是没开定位权限，需要授权
    private void locationCallBack(AMapLocation aMapLocation) {
        if (!checkGps()) {
            return;
        }
        if (aMapLocation != null) {
            L.d(TAG, aMapLocation.toString());
            String address = aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getStreetNum();
            mDataBind.tvShowAddress.setText(address);
            province = aMapLocation.getProvince();
        } else {
            mDataBind.tvShowAddress.setHint("没有获取到定位信息");
        }
    }

    private boolean checkGps() {
        LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        if (lm.getAllProviders().contains(LocationManager.GPS_PROVIDER)
            && !lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            GpsDialog.newInstance(this).setConvertListener(() -> {
                Intent intent1 = new Intent();
                intent1.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent1, 1315);
            }).show(getSupportFragmentManager());
            return false;
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1315) {
            AmapHelper.startLocation(mContext, this::locationCallBack);
        }
    }
}


